/*
 * 文件名： WechatScanServerRes.java
 * 
 * 工程名称: bis-web
 *
 * Gopay
 *
 * 创建日期： 2016年8月5日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.web.controller.scan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


/**
 * 微信扫码异步服务端通知
 *
 * @author 宣广海
 *
 * @version 
 *
 * @since 2016年8月5日
 */
@Controller
@Scope("prototype")
public class WechatScanServerRes extends ScanPayBankResBase{
	/**
	 * 定义日志对象
	 */
	private static Log logger = LogFactory.getLog(WechatScanServerRes.class);
	@RequestMapping(value ="/WechatScanPayServerRes")
	protected void execute(HttpServletRequest request,HttpServletResponse response){	    
	    logger.error("---------------WechatScanPayServerRes  bankback ---------------");
	    super.execute(request, response);
	    
	}

	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
	    String paserXml=parseRequst(request);
	    ScanPayServerNotifyMsg message =(ScanPayServerNotifyMsg)toBean(paserXml);                
        message.setBankOrderId(message.getOut_trade_no());
        message.setAmount(new BigDecimal(message.getTotal_fee()).divide(new BigDecimal(100)));
        message.setBank(BankConstants.BANK_LOGO_WECHAT);
        message.setBankBusProd(BisBankBusinessProd._16);
        message.setFront(false);
		return message;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
	    ScanPayServerNotifyMsg message =(ScanPayServerNotifyMsg)result.getModel("res");
	    OrderInfo orderInfo =new OrderInfo();
	    if(message!=null){
	        if("0".equals(message.getPay_result())){
	            orderInfo.setOrderId(message.getOrderId());
                orderInfo.setAmt(message.getAmount().toString());
                orderInfo.setNotifyNum("1");
                orderInfo.setPayStatus("00");
                orderInfo.setRetCode("00");
                orderInfo.setRetMsg("");
                orderInfo.setIsNotify(true);
                orderInfo.setBankName("wechat");
	        }else{
	            orderInfo.setOrderId(message.getOrderId());
                orderInfo.setAmt(message.getAmount().toString());
                orderInfo.setNotifyNum("1");
                orderInfo.setPayStatus("01");
                orderInfo.setRetCode("01");
                orderInfo.setRetMsg("");
                orderInfo.setIsNotify(true);
                orderInfo.setBankName("wechat");
	        }
	        
	    }
	    
		return orderInfo;
	}


	@Override
	protected boolean notifyBank(HttpServletResponse response, OrderInfo orderInfo) {	    
	    try {
	        response.setContentType("text/html;charset=GBK");
	        String notifyMsg="success";
	        logger.info("notifyBank "+orderInfo.getBankName()+" send content: \n["+notifyMsg +"]");
	        response.setContentLength(notifyMsg.getBytes().length);
            response.getOutputStream().write(notifyMsg.getBytes());
            response.getOutputStream().close();
            return true;
        } catch (IOException e) {
        	logger.info(e.getMessage());
        }
		return true;
	}

    @Override
    protected boolean checkParameters(HttpServletRequest request) {
        return true;
    }
    /** <一句话功能简述>
     * <功能详细描述>request转字符串
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public  String parseRequst(HttpServletRequest request){
        String body = "";
        ServletInputStream inputStream = null;
        BufferedReader br = null;
        try {
            inputStream = request.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            while(true){
                String info = br.readLine();
                if(info == null){
                    break;
                }
                if(body == null || "".equals(body)){
                    body = info;
                }else{
                    body += info;
                }
            }
        } catch (UnsupportedEncodingException e) {
        	logger.info(e.getMessage());
        } catch (IOException e) {
        	logger.info(e.getMessage());
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (IOException e) {
                logger.error("关闭IO流异常： ", e);
            }
        }
        return body;
    }
    public  BaseMessage toBean(String request){
        ScanPayServerNotifyMsg message = new ScanPayServerNotifyMsg();
        XStream xs = new XStream(new DomDriver());
        xs.autodetectAnnotations(true);
       // xs.ignoreUnknownElements();
        xs.toXML(message);
        message =(ScanPayServerNotifyMsg)xs.fromXML(request);
        logger.info("异步通知XML报文：  "+request);
        logger.info("支付响应对象：  "+ToStringBuilder.reflectionToString(message));
        return message;
    }

}
